//
// Created by LiuYou on 2021/10/23.
//

#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <cstring>


static int srcFd;


static void releaseResources() {
    close( srcFd );

    const char str[] = "释放文件描述符。\n.";
    write( STDOUT_FILENO, str, sizeof( str ) - 1 );
}


int main(int argc, char** argv) {
    srcFd = open( argv[1], O_RDONLY );
    atexit( releaseResources );
    char buffer[10]{};
    /*
     * Read NBYTES into BUF from FD.  Return the number read, -1 for errors or 0 for EOF.
     * 将 NBYTES(n个字节) 从 FD 读入 BUF。返回读取的数字，-1 表示错误或 0 表示 EOF。
     */
    ssize_t readBytes{};
    while ((readBytes = read( srcFd, buffer, sizeof( buffer ))) != 0) {
        if (readBytes < 0) {
            perror( "read()" );
            exit( 1 );
        }
        /*
         * Write N bytes of BUF to FD.  Return the number written, or -1.
         * 将 N 个字节的 BUF 写入 FD。返回写入的数字，或 -1。
         */
        ssize_t writeBytes{};
        int writePos{};
        while ((writeBytes = write( STDOUT_FILENO, buffer + writePos, readBytes )) != readBytes) {
            writePos += static_cast<int>(writeBytes);
            readBytes -= writePos;
        }
    }


    return 0;
}
